package com.manageserver.handler;

import com.managecommon.constant.MessageConstant;
import com.managecommon.exception.BaseException;
import com.managecommon.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @Author linye
 * @Since 1.0.0
 * @Date 2023/7/14 11:09
 * @Description 全局异常处理类，处理项目中抛出的异常
 */

@RestController
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());

        return Result.error(ex.getMessage());
    }

    /**
     * 捕获SQL异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result SQLExceptionHandler(SQLIntegrityConstraintViolationException ex){
        //Duplicate entry 'lisi' for key 'employee.idx_username'
        log.error(ex.getMessage());
        String msg  = ex.getMessage();

        if (msg.contains("Duplicate entry")){
            String split[] = msg.split(" ");
            return Result.error("用户名"+split[2]+"已存在");
        } else {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }


    }
}
